package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.bean.ShoppingCart;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.exception.CustomException;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Tang
 * @date 2023/2/25
 */
@RequestMapping("/shoppingCart")
@RestController
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> save(@RequestBody ShoppingCart shoppingCart){
        //1.调用service的新增方法
        shoppingCartService.addCart(shoppingCart);
        //2.返回结果
        return R.success(shoppingCart);
    }

    @PostMapping("/sub")
    public R<ShoppingCart> reduce(@RequestBody ShoppingCart shoppingCart){
        shoppingCartService.reduceCart(shoppingCart);
        return R.success(shoppingCart);
    }

    /**
     * 查询购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        //【注意】：根据当前登录用户id进行查询当前用户下的所有购物车数据
        //1.获取当前登录的用户id
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new CustomException("请先登录！");
        }

        //2.设置查询条件
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);

        //3.调用service的查询方法
        List<ShoppingCart> list = shoppingCartService.list(wrapper);

        //4.返回结果
        return R.success(list);
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean(){
        //【注意】：只能清空当前用户自己名下的购物车数据
        //1.获取当前登录的用户id
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new CustomException("请先登录！");
        }

        //2.设置查询条件
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);

        //3.调用service的删除方法
        boolean flag = shoppingCartService.remove(wrapper);

        //4.返回结果
        return flag ? R.success("清空购物车成功！") : R.error("清空购物车失败！");
    }
}
